package com.lhb.aicodemother.manager;

import com.lhb.aicodemother.config.CosClientConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;

/*
* COS对象存储管理器
* */
@Component
@Slf4j
public class CosManager {
    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private COSClient cosClient;

    /*
    * 上传对象
    * */
    public PutObjectResult putObject(String key, File file){
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(),key,file);
        return cosClient.putObject(putObjectRequest);
    }


    /*
    * 上传对象到COS并返回访问URL
    * */
    public String uploadFile(String key,File file){
        // 上传文件
        PutObjectResult result = putObject(key,file);
        if(result!=null){
            // 构建访问URL
            String url = String.format("%s%s",cosClientConfig.getHost(),key);
            log.info("文件上传成功：{} -> {}",file.getName(),url);
            return url;
        }else {
            log.error("文件上传COS失败，返回结果为空");
            return null;
        }
    }

}
